/*
 * @Description: 
 * @Author: chenjiaxin
 * @Date: 2021-12-21 21:02:22
 * @LastEditTime: 2021-12-26 14:56:30
 * @FilePath: \novel-serve\src\middleware\user.middleware.js
 */
const errorTypes = require("../constants/error-types");
const service = require("../service/user.service");
const md5Password = require('../utils/password-handle');

const { verifyEmail } = require("../utils/verify-handle");

const verifyUser = async (ctx, next) => {
  try {
    // 1、获取客户端用户名，和密码
    let { e_mail, password } = ctx.request.body;
    // 2、校验参数
    if (!e_mail || !password) {
      // const error = new Error(errorTypes.REGISTER_IS_REQUIRED);
      //发射一个错误信息
      return ctx.app.emit('error', errorTypes.REGISTER_IS_REQUIRED, ctx);
    }

    //校验邮箱
    if (!verifyEmail(e_mail)) {
      // const error = new Error(errorTypes.E_MAIL_ERROR);
      return ctx.app.emit('error', errorTypes.E_MAIL_ERROR, ctx);
    }

    //3、判断用户有没有注册过
    let result = await service.getUserByEmail(e_mail);
    if (result.length) {
      //注册过
      // const error = new Error(errorTypes.USER_ALREADY_EXISTS);
      return ctx.app.emit('error', errorTypes.USER_ALREADY_EXISTS, ctx);

    }

    await next();

  } catch (error) {
    return ctx.app.emit('error', errorTypes.SYNTAX_ERROR, ctx, error.message);
  }
}

const handlePassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  //密码加密
  ctx.request.body.password = md5Password(password);

  // console.log(ctx.request.body, '加密');

  await next();
}

module.exports = {
  verifyUser,
  handlePassword
}
